package com.xben.ribbonconsumer.UserCommand;

import com.netflix.hystrix.*;
import com.xben.ribbonconsumer.service.UserService;
import com.xben.ribbonconsumer.service.UsersService;
import org.apache.tomcat.jni.User;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: xben
 * @Date: 2019/1/24 14:21
 */
public class UserCollapseCommand extends HystrixCollapser<List<User>, User, Long> {

    private UsersService userService;
    private Long userId;

    public UserCollapseCommand(UsersService userService, Long userId) {
        super(Setter.withCollapserKey(HystrixCollapserKey.Factory.asKey("userCollapse"))
                .andCollapserPropertiesDefaults(
                        HystrixCollapserProperties.Setter().withTimerDelayInMilliseconds(100)));
        this.userService = userService;
        this.userId = userId;

    }

    @Override
    public Long getRequestArgument() {
        return userId;
    }

    @Override
    protected HystrixCommand<List<User>> createCommand(Collection<CollapsedRequest<User, Long>> collection) {
        List<Long> userIds = new ArrayList<>(collection.size());
        userIds.addAll(collection.stream().map(CollapsedRequest::getArgument).collect(Collectors
                .toList()));
        return new UserBatchCommand(userService, userIds);
    }

    @Override
    protected void mapResponseToRequests(List<User> users, Collection<CollapsedRequest<User, Long>> collections) {
        int count = 0;
        for (CollapsedRequest<User, Long> collection : collections) {
            User user = users.get(count++);
            collection.setResponse(user);
        }
    }


}
